#include "main.h"
#include "AppDelegate.h"
#include "cocos2d.h"
#include <iostream>
#include "../Classes/XCocos/import_xcocos.h"

class CWin32ConsoleAutoManager
{
public:
	CWin32ConsoleAutoManager()
	{
		m_bAlloced = false;

		m_bAlloced = AllocConsole();
		if (m_bAlloced)
		{
			freopen("conout$", "w", stdout);
			freopen("conout$", "w", stderr);
			std::cout << "CWin32ConsoleAutoManager: AllocConsole" << std::endl;
		}
	}

	~CWin32ConsoleAutoManager()
	{
		if (m_bAlloced)
		{
			FreeConsole();
		}
	}

private:
	BOOL m_bAlloced;
};

static CWin32ConsoleAutoManager gs_Win32ConsoleAutoManager;

// set current working dir to the exe dir
void FixWorkingDir()
{
	HANDLE hCurrentExe = ::GetModuleHandle(NULL);

	std::wstring strFileName;
	std::wstring strPath;
	strFileName.resize(MAX_PATH * 2, 0);
	::GetModuleFileName((HMODULE)hCurrentExe, const_cast<std::wstring::value_type*>(strFileName.data()), strFileName.size());

	auto nPosEnd = strFileName.find_last_of(_T('\\'));
	if (std::wstring::npos != nPosEnd)
	{
		strPath = strFileName.substr(0, nPosEnd);
		::SetCurrentDirectory(strPath.c_str());
	}
	else
	{
		//XASSERT_MSG(false, _T("windows did not have root path, \\ must be found"));
	}

}

USING_NS_CC;

int APIENTRY _tWinMain(HINSTANCE hInstance,
                       HINSTANCE hPrevInstance,
                       LPTSTR    lpCmdLine,
                       int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

	FixWorkingDir();

    // create the application instance
    AppDelegate app;
    return Application::getInstance()->run();
}


int XCOCOS_API XcocosMainRunAsDll(XCocosEditCallBack* pCallBack)
{
	FixWorkingDir();

	// create the application instance
	AppDelegate app;
	app.SetXCocosEditCallBack(pCallBack);
	return Application::getInstance()->run();
}